import ij.IJ;
import ij.ImagePlus;
import ij.measure.ResultsTable;
import ij.process.ByteProcessor;
import ij.process.ImageProcessor;

public class maskChannel {
	double ar, ca;
	ResultsTable rt;
	int row;

	public void mask_channel(ImagePlus mask_imp) {
		
		mask_imp.show();
		IJ.setAutoThreshold(mask_imp, "Default dark");
		IJ.run(mask_imp, "Convert to Mask", "");
		IJ.run(mask_imp, "Dilate", "");
		IJ.run(mask_imp, "Dilate", "");
        IJ.run(mask_imp, "Fill Holes", "");

        //ronil what the heck does this particles8 really do???
        //How many side effects is this causing???
		IJ.run("Particles8 ", "white show=Particles overwrite");

		rt = ResultsTable.getResultsTable();

		row = rt.getCounter();

		ar = 0;
		for (int i = 0; i < row; i++) {
			ca = rt.getValue("Pixels", i);
			if (ca > ar)
				ar = ca;
		}

		IJ.run("Particles8 ", "white show=Particles filter minimum=" + ar
				+ " maximum=" + ar + " overwrite");
		
		mask_imp.hide();
	}

	public ImagePlus merge_masks(ImagePlus imp_channel1, ImagePlus imp_channel2) {
		ImageProcessor p1, p2;

		p1 = imp_channel1.getProcessor();
		p2 = imp_channel2.getProcessor();

		ImageProcessor mask_p = new ByteProcessor(p1.getWidth(), p1.getHeight());
		ImagePlus merge_masks = new ImagePlus("Mask", mask_p);

		for (int y = 0; y < imp_channel1.getHeight(); y++) {
			for (int x = 0; x < imp_channel1.getWidth(); x++) {

				if ((p1.getPixel(x, y) == 255) && (p2.getPixel(x, y) == 255)) {
					mask_p.putPixel(x, y, 255);
				} else
					mask_p.putPixel(x, y, 0);
			}
		}
		return merge_masks;
	}

}